<?php
// Module Body

function nss_users_create(&$data) {
	global $cfg, $echo;
	
	// obtain the user's real username
	$uniquedata['id'] = $data['id'];
	$uniquedata['username'] = $data['username'];
	call_hook('user:get:username', $uniquedata);
	$unique = $uniquedata['username'];

	$userarray = webcp_getpwnam($unique);
	
	// Set appropriate shell
	if ($data['shell'] == "on")
		$shell = $cfg['prog']['shell'];
	else
		$shell = $cfg['prog']['noshell'];

	//code taken from user.wcp.phps
	//see if MD5 passwords are enabled, otherwise use DES (checked on redhat 7.1 - 9.0)
	if (is_readable($cfg['authconfig']) && strpos(file_get_contents($cfg['authconfig']), 'USEMD5=yes')!==false) {
		$crypt_password = crypt($data['password'], '$1$'.make_salt().'$');
	} else {
		$crypt_password = crypt($data['password'], $cfg['key']);
	}

	if (!isset($data['domain'])) {
                $SQL = 'SELECT domain FROM domains WHERE id = "'.$data['id'].'"';
                $res = mysql_query($SQL);
                if (mysql_num_rows($res)) {
                        $row = mysql_fetch_array($res);
                        $domain = $row['domain'];
                }
        } else {
                $domain = $data['domain'];
        }

	// insert the proper nss record
	webcp_log(3,0,'nss-mysql',"Creating new entry: ".$data['id'].' - '.$data['username'],0,$echo);
	$SQL = 'INSERT INTO user(id, username, user_name, realname, shell, password, status, uid, gid, homedir)
		VALUES('.$data['id'].', "'.$data['username'].'", "'.$data['username'].'@'.$domain.'", "'.$data['name'].'", "'.$shell.'", "'.$crypt_password.'", "A", '.$userarray['uid'].', '.$userarray['gid'].', "'.$data['root'].'")';
	mysql_query($SQL);
}

function nss_users_remove(&$data) {
	global $echo;
	
	// Select the correct username in case we are updating username
	$username = $data['username1'];
	
	// delete proper nss record
	$SQL = 'DELETE FROM user WHERE id = '.$data['id'].' AND username = "'.$username.'"';
	webcp_log(3,0,'nss-mysql',"Deleting old entry: ".$data['id'].' - '.$username.' with '.$SQL,0,$echo);
	mysql_query($SQL);
}

function nss_users_update(&$data) {
	// delete the old entry
	nss_users_remove($data);
	// create the new entry
	nss_users_create($data);	
}

function nss_users_suspend(&$data) {
	// lock the proper nss record
	$SQL = 'UPDATE user SET status = "L" WHERE id = '.$data['id'].' AND username = "'.$username.'"';
	mysql_query($SQL);
}

function nss_users_unsuspend(&$data) {
	// unlock the proper nss record
	$SQL = 'UPDATE user SET status = "A" WHERE id = '.$data['id'].' AND username = "'.$username.'"';
	mysql_query($SQL);
}
?>
